<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <!-- 3.点击添加角色显示对话框 -->
          <el-button type="primary" @click="showAddRoles = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['vcenter', 'bdbottom', i1 === 0 ? 'bdtop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="['vcenter', i2 === 0 ? '' : 'bdtop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      type="success"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      @close="removeRightById(scope.row, item3.id)"
                      closable
                      type="danger"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{scope.row}}
            </pre>-->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="290">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="EditorialRoles(scope.row.id)"
              icon="el-icon-edit"
              size="mini"
            >编辑</el-button>
            <el-button
              type="warning"
              @click="removeEditorialRolesById(scope.row.id)"
              icon="el-icon-delete"
              size="mini"
            >删除</el-button>
            <el-button
              @click="showSetRightDialogVislist(scope.row)"
              type="danger"
              icon="el-icon-setting"
              size="mini"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 1.添加角色 -->
    <el-dialog title="添加角色" :visible.sync="showAddRoles" width="70%">
      <el-form :model="addRoles" :rules="addRolesRules" ref="addRolesRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddRoles = false">取 消</el-button>
        <el-button type="primary" @click="AddRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色信息 -->
    <el-dialog title="编辑" :visible.sync="showEditorialRole" @close="EditorialRoleClose">
      <el-form
        :model="EditorialRoleForm"
        :rules="addRolesRules"
        ref="EditorialRoleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="EditorialRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="EditorialRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditorialRole = false">取 消</el-button>
        <el-button type="primary" @click="EditorialRoleinfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="SetRightDialogVislist" width="50%" @close="setRightDialogClose">
      <!-- 树形控件 -->
      <el-tree
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        :data="rightslist"
        :props="treeProps"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVislist = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 当前将分配权限的角色id
      roleId: '',
      // 默认选中的节点id值数组
      defkeys: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      rightslist: [],
      // 控制分配权限对话框的显示与隐藏
      SetRightDialogVislist: false,
      rolesList: [],
      // 2.定义添加角色默认隐藏
      showAddRoles: false,
      // 4.双向绑定填写信息的参数
      addRoles: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑按钮的显示对话框默认隐藏
      showEditorialRole: false,
      EditorialRoleForm: {},
      addRolesRules: {
        // 验证添加角色的规则
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3-100之间',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3-100之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.errpr('获取角色权限失败')
      }
      // this.$message.success('获取角色权限成功')
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    async AddRolesInfo() {
      this.$refs.addRolesRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('roles', this.addRoles)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        // 隐藏添加用户对话框
        this.showAddRoles = false
        // 重新获取用户列表的数据
        this.getRolesList()
      })
    },
    // 展示编辑修改用户对话框
    async EditorialRoles(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      this.EditorialRoleForm = res.data
      this.showEditorialRole = true
      // console.log(id)
    },
    // 监听修改对话框的关闭事件
    EditorialRoleClose() {
      this.$refs.EditorialRoleFormRef.resetFields()
    },
    // 编辑确定提交信息
    EditorialRoleinfo() {
      this.$refs.EditorialRoleFormRef.validate(async valid => {
        if (!valid) return
        // 发起编辑角色信息的数据请求
        const { data: res } = await this.$http.put(
          'roles/' + this.EditorialRoleForm.roleId,
          {
            roleName: this.EditorialRoleForm.roleName,
            roleDesc: this.EditorialRoleForm.roleDesc
          }
        )
        // console.log(this.EditorialRoleForm.id)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑角色信息失败！')
        }
        // 关闭对话框
        this.showEditorialRole = false
        // 刷新数据列表
        this.getRolesList()
        // 提示修改成功
        this.$message.success('编辑角色信息成功！')
      })
    },
    // 根据id删除对应的用户信息
    async removeEditorialRolesById(id) {
      // 询问用户是否删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果用户确认删除，返回值为字符串 confirm
      // 如果用户取消删除，返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getRolesList()
    },
    // 根据id删除对应的三级权限
    async removeRightById(role, rightId) {
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.info('删除权限失败')
      }
      // this.$message.success('删除权限成功')
      // this.getRolesList()
      // 直接给role.children赋值一次，这样可以防止列表的刷新
      role.children = res.data
    },
    async showSetRightDialogVislist(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      // 把获取到的权限数据保存到rightslist中
      this.rightslist = res.data
      // console.log(this.rightslist)
      this.getLeafkeys(role, this.defkeys)
      this.SetRightDialogVislist = true
    },
    // 分配权限    通过递归的形式，获取角色下所有的三级权限id，并保存到 defkeys 数组中
    getLeafkeys(node, arr) {
      if (!node.children) {
        // 如果当前 node 节点不包含 children 属性， 则是三级节点
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafkeys(item, arr)
      })
    },
    // 监听分配对话框的关闭事件
    setRightDialogClose() {
      this.defkeys = []
    },
    // 点击确定按钮为角色分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.SetRightDialogVislist = false
    }
  }
}
</script>
<style lang="less" scoped>
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-row {
  margin: 0;
  padding-top: 10px;
  padding-bottom: 10px;
}
.el-tag {
  margin-right: 10px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
